<?php

namespace App\Rules;

use Illuminate\Support\Facades\Validator;
class ArrValidator  extends BaseRules
{
    private int $index = 0;  //坐标
    private mixed $validatorEditor = null;  //错误收集器

    public function __construct(
        public readonly  array $validator,
    ) {
    }


    /**
     * 判断是否通过验证规则
     *
     * @param  string  $attribute 检测的字段
     * @param  mixed   $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        foreach($value as $key => $val){
            $validator =  Validator::make($val, $this->validator);
            if ($validator->fails()) {
                $this->validatorEditor = $validator;
                $this->index = $key ;
                return false;  //数据验证错误
            }
        }
        return true;
    }

    /**
     * 获取校验错误信息
     *
     * @return string
     */
    public function message()
    {
        return ":attribute  下标{$this->index}  {$this->validatorEditor?->errors()->first()}";
    }
}
